package com.taplinker.client.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

import com.taplinker.client.R;
import com.taplinker.core.util.ImageUtil;

@SuppressLint("NewApi")
public class RoundImageView extends ImageView {
	private float rectX = 0f;
	private float rectY = 0f;

	private Paint paint = new Paint();

	public RoundImageView(Context context) {
		super(context);
		
		if (android.os.Build.VERSION.SDK_INT > 10) {
			setLayerType(View.LAYER_TYPE_SOFTWARE, null);  
		}
	}
	
	public void setRectX(float rectX) {
		this.rectX = rectX;
	}

	public void setRectY(float rectY) {
		this.rectY = rectY;
	}

	public RoundImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		
		if (android.os.Build.VERSION.SDK_INT > 10) {
			setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		}
		
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RandRectImage);
		
		rectX = a.getInt(R.styleable.RandRectImage_rx, 0);
		rectY = a.getInt(R.styleable.RandRectImage_ry, 0);
		
		int strokeWidth = a.getInt(R.styleable.RandRectImage_stokeWidth, 0);
		int stokeColor = a.getColor(R.styleable.RandRectImage_stokeColor, 0);
		
		initStrokePaint(strokeWidth, stokeColor);   
	}

	protected void initStrokePaint(int width, int stokeColor) {
		paint.setColor(stokeColor);
		paint.setStrokeWidth(ImageUtil.dip2px(getContext(), width));
		paint.setAntiAlias(true);
		paint.setStyle(Paint.Style.STROKE);
	}
	
	public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		
		if (android.os.Build.VERSION.SDK_INT > 10) {
			setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		}
		
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RandRectImage);
		
		rectX = a.getInt(R.styleable.RandRectImage_rx, 0);
		rectY = a.getInt(R.styleable.RandRectImage_ry, 0);
		
		int strokeWidth = a.getInt(R.styleable.RandRectImage_stokeWidth, 0);
		int stokeColor = a.getColor(R.styleable.RandRectImage_stokeColor, 0);
		
		initStrokePaint(strokeWidth, stokeColor);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		Path clipPath = new Path();
		int w = this.getWidth();
		int h = this.getHeight();
		clipPath.addRoundRect(new RectF(0, 0, w, h), rectX, rectY, Path.Direction.CW);
		canvas.clipPath(clipPath);
		
		super.onDraw(canvas);
		
		clipPath = new Path();
		clipPath.addRoundRect(new RectF(0, 0, w, h), rectX, rectY, Path.Direction.CW);
		canvas.drawPath(clipPath, paint);
	}

}
